package com.anywhere.freightman.system.controller;

import com.anywhere.freightman.common.ContextKeys;
import com.anywhere.freightman.common.annotation.Permission;
import com.anywhere.freightman.common.entity.ReturnResp;
import com.anywhere.freightman.common.entity.user.Account;
import com.anywhere.freightman.system.controller.request.UpdatePwdRequest;
import com.anywhere.freightman.system.model.AccessToken;
import com.anywhere.freightman.system.service.IAccessTokenService;
import com.anywhere.freightman.system.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("admin/member")
@Api(tags = "个人中心")
public class MemberController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IAccessTokenService accessTokenService;

    @PutMapping("pwd")
    @ApiOperation("密码修改")
    @Permission(code = "COMMON")
    public ReturnResp updatePwd(HttpServletRequest httpRequest,
                                @RequestBody UpdatePwdRequest request) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        userService.updatePwd(account.getId(), request.getOldPwd(), request.getNewPwd());
        return ReturnResp.buildOk();
    }

    @PostMapping("logout")
    @ApiOperation("注销")
    @Permission(code = "COMMON")
    public ReturnResp logout(HttpServletRequest httpRequest) {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        AccessToken token = accessTokenService.getByUserId(account.getId());
        if (token != null) {
            accessTokenService.logout(token.getUserId(), token.getType());
        }
        return ReturnResp.buildOk();
    }
}
